package cn.caidabao.camunda_demo.service.impl;

import cn.caidabao.camunda_demo.annotation.CaiProcessFormField;
import cn.caidabao.camunda_demo.pojo.po.TCaiProcessFormField;
import cn.caidabao.camunda_demo.mapper.TCaiProcessFormFieldMapper;
import cn.caidabao.camunda_demo.service.ITCaiProcessFormFieldService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cai
 * @since 2024-07-16
 */
@Service
public class TCaiProcessFormFieldServiceImpl extends ServiceImpl<TCaiProcessFormFieldMapper, TCaiProcessFormField> implements ITCaiProcessFormFieldService {

    @SneakyThrows
    @Override
    public List<TCaiProcessFormField> getFieldsByClass(String caiFormClassName) {
        Class<?> formClass = ClassLoader.getSystemClassLoader().loadClass(caiFormClassName);
        Field[] declaredFields = formClass.getDeclaredFields();
        List<TCaiProcessFormField> res = new ArrayList<>();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            CaiProcessFormField annotation = declaredField.getAnnotation(CaiProcessFormField.class);
            if (annotation!=null){
                TCaiProcessFormField formField = new TCaiProcessFormField();
                String fieldName = annotation.fieldName();
                fieldName = StringUtils.isBlank(fieldName)?declaredField.getName():fieldName;
                formField.setFieldName(fieldName);
                formField.setFieldType(annotation.fieldType());
                formField.setCheckType(annotation.checkType());
                formField.setDefaultValue(annotation.defaultValue());
                formField.setEditable(annotation.editEnable()?1:0);
                formField.setRequired(annotation.required());
                formField.setShowType(annotation.showType());
                formField.setDetailFieldName(annotation.detailFieldName());
                formField.setIsCamundaVariable(annotation.isCamundaVariable()?1:0);
                res.add(formField);
            }
        }
        return res;
    }

    @Override
    public List<TCaiProcessFormField> getFieldsByFormId(String caiFormId) {
        return this.lambdaQuery().eq(TCaiProcessFormField::getFormId,caiFormId).list();
    }
}
